#include "imageloader.h"

#include "picopng.cpp"
#include <iostream>

int ImageLoader::loadImagePNG(std::vector<unsigned char>& image, unsigned long &width, unsigned long &height, const std::string filename)
{
	std::vector<unsigned char> buffer;
	loadFile(buffer, filename);
	unsigned long w,h;
	int error = decodePNG(image, w, h, buffer.empty() ? 0 : &buffer[0], (unsigned long)buffer.size());
	width = w;
	height = h;

	//if there's an error, display it
	if(error != 0)
	{
		std::cout << "PicoPNG error: " << error << std::endl;
		if(error == 48) std::cout << filename.c_str() <<  " missing?" << std::endl;//the given data is empty
		return 1;
	}
	return 0;
}

void ImageLoader::loadFile(std::vector<unsigned char>& buffer, const std::string& filename) //designed for loading files from hard disk in an std::vector
{
  std::ifstream file(filename.c_str(), std::ios::in|std::ios::binary|std::ios::ate);

  //get filesize
  std::streamsize size = 0;
  if(file.seekg(0, std::ios::end).good()) size = file.tellg();
  if(file.seekg(0, std::ios::beg).good()) size -= file.tellg();

  //read contents of the file into the vector
  if(size > 0)
  {
	buffer.resize((size_t)size);
	file.read((char*)(&buffer[0]), size);
  }
  else buffer.clear();
}